import sys, traceback, Ice
import Chat
import time

class UserI(Chat.MessageReceiver):
    def onMessage(self, user, message, context=None):
        print(user,":",message)

status =   0
ic  =  None
try: 
    ic  =   Ice.initialize(sys.argv)
    base  =   ic.stringToProxy( "ChatRoom:default -p 12345" )
    chat  =   Chat.RoomPrx.checkedCast(base)
    if not chat:
        raise   RuntimeError( "Invalid proxy" )
    
    adapter  =   ic.createObjectAdapterWithEndpoints( "ChatUser" ,  "default" )
    obj   =   UserI()
    adapter.add( obj , ic.stringToIdentity( "ChatUser" ))
    adapter.activate()
    
    userPrx = Chat.MessageReceiverPrx.uncheckedCast(adapter.createProxy(ic.stringToIdentity("ChatUser")))
    
    print("input username: ",end="")
    username = input()
    if chat.login(username, userPrx ) == 0:
        print("login error: User Name already exist")
        exit()
    print("login OK")

    chat.broadcast(username, "---login---")
    while 1:
        chat.printUserList()
        msg = input()
        if msg == "exit":
            chat.logout(username)
            chat.broadcast(username, "---logout---")
            break
        chat.broadcast(username, msg)
    # time.sleep(100)

except :
    traceback.print_exc()
    status  =   1
if  ic:
    # Clean up
    try :
        ic.destroy()
    except :
        traceback.print_exc()
        status  =   1
sys.exit(status)
